
/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
 
import grammar.Design;
import grammar.InstantiationInput;
import grammar.Match;
import grammar.Matcher;
import grammar.Rule;

import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

import test.ShapeAnneal;
import test.TestData;
import test.PoleBarn;
 
import java.awt.event.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
@SuppressWarnings("all")
/*
 * InternalFrameDemo.java requires:
 *   MyInternalFrame.java
 */
public class GrammarGui extends JFrame
                               implements ActionListener {
    JDesktopPane desktop;
 
    public GrammarGui() {
        super("InternalFrameDemo");
 
        //Make the big window be indented 50 pixels from each edge
        //of the screen.
        int inset = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(inset, inset,
                  screenSize.width  - inset*2,
                  screenSize.height - inset*2);
 
        //Set up the GUI.
        desktop = new JDesktopPane(); //a specialized layered pane
        createFrame(); //create first "window"
        setContentPane(desktop);
        setJMenuBar(createMenuBar());
 
        //Make dragging a little faster but perhaps uglier.
        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    }
 
    protected JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
 
        //Set up the lone menu.
        JMenu menu = new JMenu("Document");
        menu.setMnemonic(KeyEvent.VK_D);
        menuBar.add(menu);

        JMenu ruleMenu = new JMenu("Rules");
        menuBar.add(ruleMenu);
        
        //Set up the first menu item.
        JMenuItem menuItem = new JMenuItem("New");
        menuItem.setMnemonic(KeyEvent.VK_N);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_N, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("new");
        menuItem.addActionListener(this);
        menu.add(menuItem);
 
        //Set up the second menu item.
        menuItem = new JMenuItem("Quit");
        menuItem.setMnemonic(KeyEvent.VK_Q);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_Q, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("quit");
        menuItem.addActionListener(this);
        menu.add(menuItem);

        
        //Set up the first rule menu item.
        menuItem = new JMenuItem("Apply rule 1");
        menuItem.setActionCommand("rule1");
        menuItem.addActionListener(this);
        ruleMenu.add(menuItem);
        
        return menuBar;
    }
 
    //React to menu selections.
    public void actionPerformed(ActionEvent e) {
        if ("new".equals(e.getActionCommand())) { //new
            createFrame();
        } else if("rule1".equals(e.getActionCommand())) {
            executeRule();
        } else { //quit
            quit();
        }
    }
 
    private void executeRule() {
        
    }

    //Create a new internal frame.
    protected void createFrame() {
        Design design = shapeGrammarMain();//grammarMain();
        
        GeomFrame frame1 = new GeomFrame(design);
        
        frame1.setVisible(true); //necessary as of 1.3
        desktop.add(frame1);
        try {
            frame1.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {}
        
        GraphFrame2 frame2 = new GraphFrame2(design.getComboGraph());
        frame2.setVisible(true); //necessary as of 1.3
        desktop.add(frame2);
        try {
            frame2.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {}

//        RuleGeomFrame ruleFrame = new RuleGeomFrame();
//        ruleFrame.setVisible(true); 
//        desktop.add(ruleFrame);
//        try {
//            ruleFrame.setSelected(true);
//        } catch (java.beans.PropertyVetoException e) {}
//
//        RuleGraphFrame ruleGraphFrame = new RuleGraphFrame();
//        ruleGraphFrame.setVisible(true); 
//        desktop.add(ruleGraphFrame);
//        try {
//            ruleGraphFrame.setSelected(true);
//        } catch (java.beans.PropertyVetoException e) {}
    }
    
    private Design shapeGrammarMain() {
        // build/read rules and initial condition
    	
    	//To build snake :
        Design design = ShapeAnneal.buildInitialConfiguration();
        Rule rule1 = ShapeAnneal.straight();
        Rule rule2 = ShapeAnneal.counterClockwise();
        Rule rule3 = ShapeAnneal.clockwise();
    	

        java.util.List<Rule> rules = new ArrayList<Rule>();
        rules.add(rule1);
        rules.add(rule2);
        rules.add(rule3);

        Random rand = new Random(System.currentTimeMillis());
        
//        build/read script
        for (int j = 0; j<25; j++) {        
            //where is rule 1 applicable
            Rule rule = (Rule) chooseRandom(rules, rand);
            System.out.println("rule number chosen = " + rules.indexOf(rule));
            
            java.util.List<Match> matches = Matcher.findRuleMatches(design, rule);
            System.out.println("number of matches = " + matches.size());
            
            if (matches.isEmpty()) {
                continue;
            }
            
            //choose where to apply rule
            Match match = matches.get(matches.size()-1);

//          apply rule and instantiate needed parameters
            InstantiationInput input = new InstantiationInput();
            rule.apply(design, match, input);
        }
        design.writeVRML("design.wrl");
        return design;
    }



	//////////////////////////Applies rules when there is a match//////////////////
    private void applyIfNotEmpty(List<Match> matches, Rule rule, Design design, InstantiationInput input) {
    	if (matches.isEmpty()==false) {
    		Match match = matches.get(matches.size()-1);
    		rule.apply(design, match, input);
    	}
	}
    ///////////////////////////////////////////////////////////////////////////////
    
	private Object chooseRandom(List<? extends Object> list, Random rand) {
        int randInt = rand.nextInt(list.size()); 
        return list.get(randInt);
    }
     
    private Design grammarMain() {
        // build/read rules and initial condition
    	
    	//To build spiral uncomment these 4 lines below:
        Design design = TestData.buildInitialSpiral();
        Rule rule1 = TestData.buildRuleSpiral1();
        Rule rule2 = TestData.buildRuleSpiral2();
        Rule rule3 = TestData.buildRuleSpiral3();
    	
    	//To build pole barn
//        Design design = PoleBarn.buildInitialBarn();
//        Rule rule1 = PoleBarn.anchortoground();
//        Rule rule2 = PoleBarn.posttoanchor();
//        Rule rule3 = PoleBarn.bendtopost();
//        Rule rule4 = PoleBarn.posttobend();
//        Rule rule5 = PoleBarn.bendtopost2();

        java.util.List<Rule> rules = new ArrayList<Rule>();
        rules.add(rule1);
        rules.add(rule2);
        rules.add(rule3);
//        rules.add(rule4);
//        rules.add(rule5);

        Random rand = new Random(System.currentTimeMillis());
        
//        build/read script
        for (int j = 0; j<25; j++) {        
            //where is rule 1 applicable
            Rule rule = (Rule) chooseRandom(rules, rand);
            System.out.println("rule number chosen = " + rules.indexOf(rule));
            
            java.util.List<Match> matches = Matcher.findRuleMatches(design, rule);
            System.out.println("number of matches = " + matches.size());
            
            if (matches.isEmpty()) {
                continue;
            }
            
            //choose where to apply rule
            Match match = matches.get(matches.size()-1);
            System.out.println((matches.size()-1));

//          apply rule and instantiate needed parameters
            InstantiationInput input = new InstantiationInput();
            rule.apply(design, match, input);
        }
        design.writeVRML("design.wrl");
        return design;
    }

    //Quit the application.
    protected void quit() {
        System.exit(0);
    }
 
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
 
        //Create and set up the window.
        GrammarGui frame = new GrammarGui();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Display the window.
        frame.setVisible(true);
    }
 
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}